<?php
/**	
*	FILENAME: 		/admin_app/security.php
*	DESCRIPTION:	This library defines commonly used security functions for the MyNova Mobile administrative interface.
*	AUTHOR:			Casey Burkhardt
*	VERSION:		1.0.0
*	LAST MODIFIED:	12/20/2009
**/

require_once("../libraries/database.php");
require_once("../libraries/functions.php");

global $COOKIE_EXPIRE_PERIOD;
$COOKIE_EXPIRE_PERIOD = 3600;

/**
*	DESCRIPTION:	Sets authentication credentials for an administrative user given the `users`.`uid` value from the database.
**/
function authenticateAdminUser($userID)
{
	global $COOKIE_EXPIRE_PERIOD;
	session_start();
	setcookie("admin_session_active", 1, time() + $COOKIE_EXPIRE_PERIOD);
	$_SESSION["uid"] = $userID;
}

/**
*	DESCRIPTION:	Enforces administrative authentication on the current page.  Returns the user ID of the `users`.`uid` record associated with the administrative account.
**/
function protectPage()
{
	session_start();
	$REJECTION_PAGE = "nocookie.php";
	// A cookie that contains the value "1" if a session is currently active, or doesn't exist if the session is expired.
	$sessionMarker = $_COOKIE["admin_session_active"];
	// The `users`.`uid` database value for the administrative user.
    $userID = $_SESSION["uid"];
    
    if ($_COOKIE["admin_session_active"] == 1 && isset($_SESSION["uid"]))
    {
		// Extend the expiration of the session marker cookie by 1 hour.
        setcookie("admin_session_active", 1, time()+36000);
    }
	else
    {
		// Session has expired or no valid session exists
        header("Location: " . $REDIRECTION_PAGE);
        die();
    }
}

/**
*	DESCRIPTION:	Determines if an active MyNova Mobile Administration Panel session exists
**/
function activeSessionExists()
{
	session_start();
	$REJECTION_PAGE = "nocookie.php";
	// A cookie that contains the value "1" if a session is currently active, or doesn't exist if the session is expired.
	$sessionMarker = $_COOKIE["admin_session_active"];
	// The `users`.`uid` database value for the administrative user.
    $userID = $_SESSION["uid"];
    
    if ($_COOKIE["admin_session_active"] == 1 && isset($_SESSION["uid"]))
    {
		// Extend the expiration of the session marker cookie by 1 hour.
        setcookie("admin_session_active", 1, time()+36000);
        return TRUE;
    }
	else
    {
		// Session has expired or no valid session exists
		return FALSE;
    }
}

/**
*	DESCRIPTION:	Returns the user ID of the active user and FALSE if no session exists
**/
function getCurrentSessionsUser()
{
	session_start();
	// A cookie that contains the value "1" if a session is currently active, or doesn't exist if the session is expired.
	$sessionMarker = $_COOKIE["admin_session_active"];
	// The `users`.`uid` database value for the administrative user.
    $userID = $_SESSION["uid"];
    
    if ($_COOKIE["admin_session_active"] == 1 && isset($_SESSION["uid"]))
    {
        return $userID;
    }
	else
    {
		return FALSE;
    }
}

/**
*	DESCRIPTION:	Processes a logout event by destroying the current session and expiring the active session marker cookie
**/
function processLogout()
{
    session_start();
    session_destroy();
    setcookie("admin_session_active", "", time()-36000);
}

/**
*	DESCRIPTION:	Logs a failed login attempt from a given IP address.  Incrementes associative value in `login_failures`.`attempts`
**/
function logFailedLoginAttempt($ipUsed, $ldapUsed)
{
	setTimezone();
	connectToDatabase();
	$sql = "SELECT *
			FROM `login_failures`
			WHERE `ip_address` = '" . $ipUsed . "';";
	$result = mysql_query($sql) or die(mysql_error());  
	if (mysql_num_rows($result) > 0)
	{
		while ($row = mysql_fetch_array($result))
		{
			$ipAddress = $row["ip_address"];
			$loginAttempts = $row["attempts"];
		}
		$sql = "UPDATE `login_failures` 
				SET `attempts` = '" . ((int)$loginAttempts + 1) . "', `last_ldap_used` = '" . $ldapUsed . "', `last_attempt_time` = '" . time() . "' 
				WHERE `ip_address` = '" . $ipUsed . "';";
	}
	else
	{
        $sql = "INSERT into `login_failures` (`ip_address`,`attempts`,`last_ldap_used`,`last_attempt_time`) 
				VALUES ('" . $ipUsed . "', '" . 1 . "', '" . $ldapUsed . "', '" . time() . "');";
    }
    mysql_query($sql) or die(mysql_error());
}

/**
*	DESCRIPTION:	Returns the number of failed login attempts from a given IP address.
**/
function getFailedAttempts($ipAddress)
{
	connectToDatabase();
	$sql = "SELECT `attempts` 
			FROM `login_failures` 
			WHERE `ip_address` = '" . $ipAddress . "';";
	$result = mysql_query($sql) or die(mysql_error());
	while ($row = mysql_fetch_array($result))
	{
		$failedAttempts = $row["attempts"];
	}
	if (mysql_num_rows($result) == 0)
	{
		$failedAttempts = 0;
	}
	return $failedAttempts;
}

/**
*	DESCRIPTION:	Removes failed login attempt records from a given IP address
**/
function removeFailedAttempts($ipAddress)
{
	connectToDatabase();
	$sql = "DELETE 
			FROM `login_failures` 
			WHERE `ip_address` = '" . $ipAddress . "'; ";
	mysql_query($sql) or die(mysql_error());
}
?>